import java.util.*;

public class 三数之和 {
    
    public static void main(String[] args) {
        

        

    }

    public List<List<Integer>> threeSum(int[] nums) {
        
        List<List<Integer>> result = new ArrayList();

        if(null == nums || nums.length < 3){

            return result;
        }

        //排序
        Arrays.sort(nums);

        for(int i=0; i<nums.length; i++){


            if(nums[i] >0){

                break;
            }

            if(i > 0 && nums[i] == nums[i-1]){

                continue;
            }

            int left = i+1;
            int right = nums.length - 1;

            while (left < right) {
                
                //求和
                int sum = nums[i] + nums[left] + nums[right];

                if(0 == sum){

                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    //这里判断的意义是去重
                    //针对的是三元组相同
                    while(left < right && nums[left] == nums[left+1]){
                        left++;
                    }
                    while(left < right && nums[right] == nums[right-1]){
                        right--;
                    }
                    left++;
                    right--;
                }  else if(sum < 0){
                    left++;
                }else{
                    right--;
                }

            }


        }


        return result;
    }
}
